import pymysql

class Mysql:
    def __init__(self, host, port, user, password, database, charset):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset

    def update(self, sql, data=None):
        db = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.database,
            charset=self.charset

        )
        try:
            with db.cursor() as cursor:
                if data:  # 如果有数据，使用 executemany
                    cursor.executemany(sql, data)
                else:
                    cursor.execute(sql)
                db.commit()
                print("数据操作成功！")
        except Exception as e:
            print(f"数据操作失败！", e)
        finally:
            db.close()

    def select(self, sql, data=None):
        db = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.database,
            charset=self.charset

        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql, data)
                result = cursor.fetchall()
                return result
        except Exception as e:
            print(f"数据查询失败！", e)
        finally:
            db.close()